package com.itheima.reggie.config;


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis配置类
 * 自定义template序列化方式:
 * 可读性有了很大提升,将java对象自动序列化成json对象,并且查询时能自动反序列化成java对象
 * 而且序列化时携带了类路径,为了查询时自动反序列化,会带来额外的开销,不自定义的话性能也就会降低
 */
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory connectionFactory){
            RedisTemplate<String, Object> template = new RedisTemplate<>();
//        设置连接工厂
        template.setConnectionFactory(connectionFactory);
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
                ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
    //注册jackson序列化器
//         key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
//         hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
//         value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
//         hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
//
        template.afterPropertiesSet();
                return template;


//        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
////        设置连接工厂
//        redisTemplate.setConnectionFactory(connectionFactory);
////        创建json序列化工具
////        Jackson2JsonRedisSerializer<Object> objectJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
////        默认的Key序列化器为：JdkSerializationRedisSerializer,让键序列化时在黑窗口可以看懂
//        redisTemplate.setKeySerializer(RedisSerializer.string());
//        redisTemplate.setHashKeySerializer(RedisSerializer.string());
////        设置value的序列化
//        redisTemplate.setValueSerializer(new StringRedisSerializer());
//        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
//        return redisTemplate;

    }
}
